import React, { PureComponent } from 'react';
import styled from 'styled-components';
import PropTypes from 'prop-types';
import { FormattedMessage } from 'react-intl';
import { FaHeart, FaRegHeart, FaRegComment } from 'react-icons/fa';
import AnswerService from 'service/RequestServices/AnswerService';
import MediumBadge from './MediumBadge';
import Ai3Q from './Ai3Q';

const AnswerSocialBarRoot = styled.div`
  display: flex;
  justify-content: left;
`;

class AnswerSocialBar extends PureComponent {
  state = {
    loading: false,
    supported: this.props.data.supported,
    counts: this.props.data.supportersCounts
  };

  upvote = () => {
    const { id } = this.props;
    let { loading, supported, counts } = this.state;
    loading = true;
    this.setState({ loading }, () => {
      AnswerService.postAnswerSupporter(id).then(() => {
        loading = false;
        supported = true;
        counts += 1;
        this.setState({ loading, supported, counts });
      });
    });
  };

  downvote = () => {
    const { id } = this.props;
    let { loading, supported, counts } = this.state;
    loading = true;
    this.setState({ loading }, () => {
      AnswerService.deleteAnswerSupporter(id).then(() => {
        loading = false;
        supported = false;
        counts -= 1;
        this.setState({ loading, supported, counts });
      });
    });
  };

  render() {
    const { onClickComment } = this.props;
    const { loading, supported, counts } = this.state;

    const active = !loading && supported;
    const unActive = !loading && !supported;

    return (
      <AnswerSocialBarRoot>
        {loading && (
          <MediumBadge key="loading" active IconComponent={<Ai3Q />}>
            <FormattedMessage id="upvote" /> {counts}
          </MediumBadge>
        )}
        {active && (
          <MediumBadge key="active" active IconComponent={<FaHeart />} onClick={this.downvote}>
            <FormattedMessage id="upvote" /> {counts}
          </MediumBadge>
        )}
        {unActive && (
          <MediumBadge key="normal" IconComponent={<FaRegHeart />} onClick={this.upvote}>
            <FormattedMessage id="upvote" /> {counts}
          </MediumBadge>
        )}
        <MediumBadge IconComponent={<FaRegComment />} onClick={onClickComment}>
          <FormattedMessage id="comments" /> {this.props.data.commentsCounts}
        </MediumBadge>
      </AnswerSocialBarRoot>
    );
  }
}

AnswerSocialBar.propTypes = {
  id: PropTypes.number.isRequired,
  data: PropTypes.shape({
    supported: PropTypes.bool.isRequired,
    supportersCounts: PropTypes.number.isRequired,
    commentsCounts: PropTypes.number.isRequired
  }).isRequired,
  onClickComment: PropTypes.func.isRequired
};

export default AnswerSocialBar;
